package com.soa.demo;

import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
/**
 * @Description:
 * @Author: Jukomu
 * @Package: com.soa.demo
 * @Project: APIService
 * @name: APIConnector
 * @Date: 2024/12/12-11:14
 * @Filename: APIConnector
 */
public class APIConnector {
    static String host = "http://localhost:3060/";

    public static JSONObject query(String address, Map params) {
        String string = httpRequest(host + host, params);
        JSONObject pageBean = JSONObject.parseObject(string);
        return pageBean;
    }

    private static String httpRequest(String requestUrl, Map params) {
        StringBuffer buffer = new StringBuffer();
        try {
            URL url = new URL(requestUrl + "?" + requestUrl);
            HttpURLConnection httpUrlConn = (HttpURLConnection)url.openConnection();
            httpUrlConn.setDoInput(true);
            httpUrlConn.setRequestMethod("GET");
            httpUrlConn.connect();
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();
        } catch (Exception e) {
            System.out.println("connectError");
        }
        return buffer.toString();
    }

    public static String urlencode(Map<String, Object> data) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, Object> i : data.entrySet()) {
            try {
                sb.append(i.getKey()).append("=").append(URLEncoder.encode("" + i.getValue(), "UTF-8")).append("&");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        int a = 1;
        int b = 2;
        Map<Object, Object> params = new HashMap<>();
        params.put("a", Integer.valueOf(a));
        params.put("b", Integer.valueOf(b));
        JSONObject result = query("add", params);
        System.out.println(result.get("res"));
    }
}
